<?php
/**
 * Ora 在线更新功能类库
 *  @author lan7
 *  @copyright lan7.net
 *
 */
class update_lib{
	/**
	 * 获取远程文件大小
	 *
	 * @param unknown_type $url
	 */
	static function getRemoteFileSize($url){
		$urlInfo = parse_url($url);
		return self::remoteFileSize($urlInfo['host'],$url);
	}

	/**
	 * 读取头信息
	 *
	 * @param unknown_type $res
	 * @return unknown
	 */
	static function readHeader($res){
		$i=0;
		$header = "";
		while( true && $i<20 ){
			$s = fgets($res,4096);
			$header .= $s;
			if( strcmp( $s, "\r\n" ) == 0 || strcmp( $s, "\n" ) == 0 )
			break;
			$i++;
		}
		if( $i >= 20 ){
			return false;
		}
		return $header;
	}

	/**
	 * 获取远程文件大小 实现函数
	 *
	 * @param unknown_type $host
	 * @param unknown_type $url
	 * @param unknown_type $counter302
	 * @return unknown
	 */
	static function remoteFileSize( $ipaddress, $url, $counter302 = 5 ){
		$socket = fsockopen( $ipaddress, 8080 );
		if(!$socket){
			return false;
		}
		// 只发送请求头信息
		$head = "HEAD $url HTTP/1.0\r\nConnection: Close\r\nHOST:$ipaddress\r\n\r\n";
		fwrite( $socket, $head );
		$header = self::readHeader($socket );
		if(!$header){
			return false;
		}
		fclose($socket);
		// check for "Location" header
		$locationMarker = "Location: ";
		$pos = strpos( $header, $locationMarker );
		if($pos > 0){
			$counter302--;
			if( $counter302 < 0 ){
				return 0;
			}
			$end = strpos( $header, "\n", $pos );
			$location = trim( substr( $header, $pos + strlen( $locationMarker ), $end - $pos - strlen( $locationMarker ) ), "\\r\\n" );
			return self::getRemoteFileSize($location);
		}
		$regex = '/Content-Length:\s([0-9].+?)\s/';
		$count = preg_match($regex, $header, $matches);
		if(isset($matches[1])){
			$size = $matches[1];
		}else{
			$size = 0;
		}
		return $size;
	}

	static function getFile($url,$savePath=THEMES_PATH){
		set_time_limit(0);
		$fileName = $savePath."/update_".time().".zip";
		$fileSize = self::getRemoteFileSize($url);
		$hdl = fopen($url, "rb");
		$count = 0;
		$downLoad = 0;
		if($hdl){
			$fp = fopen($fileName,'wb');
			while (!feof($hdl)) {
				if($count % 50 === 0){
					file_put_contents(UPLOAD_PATH."now",round(($downLoad/$fileSize),2)*100);
				}
				fputs($fp,fread($hdl, 1024));
				$count++;
				$downLoad+= 1024;
			}

		}
		file_put_contents(UPLOAD_PATH."now",100);
		fclose($fp);
		fclose($hdl);
		return $fileName;
	}
}
?>